#include "Character.h"
#include "Map.h"

Character::Character ()
{}
Character::~Character ()
{}

void Character::Load ()
{
	mSprite.Load ("Pikachu.png");
}
void Character::Render (const SVector2& screenOffset)
{
	const int width = mSprite.GetWidth ();
	const int height = mSprite.GetHeight ();
	SVector2 offset ((width * 0.5f), (height * 0.5f));
	SVector2 renderPosition = ((mPosition - offset) - screenOffset);

	mSprite.SetPosition (renderPosition);
	mSprite.Render ();
}
void Character::Unload ()
{
	mSprite.Unload ();
}
void Character::Update (float deltaTime, const Map& map)
{
	const float kSpeed = 300.0f;
	float displacementX = 0.0f;

	if (Input_IsKeyDown (Keys::RIGHT))
	{
		displacementX = (kSpeed * deltaTime);
	}
	else if (Input_IsKeyDown (Keys::LEFT))
	{
		displacementX = -(kSpeed * deltaTime);
	}

	SRect xBoundingBox = (GetBoundingBox () + SVector2 (displacementX, 0.0f));
	if (displacementX > 0.0f)
	{
		//check right
		SLineSegment segment = xBoundingBox.GetRightSegment ();
		SRect collisionBox;

		if (map.TestCollision (segment, collisionBox))
		{
			displacementX -= (xBoundingBox.max.x - collisionBox.min.x + 1.0f);
			mPosition.x += (int)displacementX;
		}
		else
		{
			mPosition.x += (int)displacementX;
		}
	}
	else if (displacementX < 0.0f)
	{
		//check left
		SLineSegment segment = xBoundingBox.GetLeftSegment ();
		SRect collisionBox;

		if (map.TestCollision (segment, collisionBox))
		{
			displacementX -= (xBoundingBox.min.x - collisionBox.max.x - 1.0f);
			mPosition.x += (int)displacementX;
		}
		else
		{
			mPosition.x += (int)displacementX;
		}
	}

	float displacementY = 0.0f;
	if (Input_IsKeyDown (Keys::UP))
	{
		displacementY = -(kSpeed * deltaTime);
	}
	else if (Input_IsKeyDown (Keys::DOWN))
	{
		displacementY = (kSpeed * deltaTime);
	}

	SRect yBoundingBox = (GetBoundingBox () + SVector2 (0.0f, displacementY));
	if (displacementY > 0.0f)
	{
		//check bottom
		SLineSegment segment = yBoundingBox.GetBottomSegment ();
		SRect collisionBox;

		if (map.TestCollision (segment, collisionBox))
		{
			displacementY -= (yBoundingBox.max.y - collisionBox.min.y + 1.0f);
			mPosition.y += (int)displacementY;
		}
		else
		{
			mPosition.y += (int)displacementY;
		}
	}
	else if (displacementY < 0.0f)
	{
		//check top
		SLineSegment segment = yBoundingBox.GetTopSegment ();
		SRect collisionBox;

		if (map.TestCollision (segment, collisionBox))
		{
			displacementY -= (yBoundingBox.min.y - collisionBox.max.y - 1.0f);
			mPosition.y += (int)displacementY;
		}
		else
		{
			mPosition.y += (int)displacementY;
		}
	}
}

SRect Character::GetBoundingBox () const
{
	SRect boundingBox;

	boundingBox.min.x = mPosition.x - 32.0f;
	boundingBox.max.x = mPosition.x + 32.0f;
	boundingBox.min.y = mPosition.y - 48.0f;
	boundingBox.max.y = mPosition.y + 48.0f;

	return boundingBox;
}